package demo9;

import demo8.CombinerJob;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

import java.io.IOException;

public class DefaultPartitionJob {

    public static void main(String[] args) throws Exception{
        // 1. 初始化配置
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://hadoop10:9000");
        //2. 创建job
        Job job = Job.getInstance(conf);
        job.setJarByClass(DefaultPartitionJob.class);

        //3. 设置输入格式化工具和输出格式化
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);

        //4. 设置输入路径和输出路径
        TextInputFormat.addInputPath(job, new Path("/mapreduce/demo9/defaultPartition.txt"));
        TextOutputFormat.setOutputPath(job, new Path("/mapreduce/demo9/out"));

//        TextInputFormat.addInputPath(job, new Path(args[0]));
//        TextOutputFormat.setOutputPath(job, new Path(args[1]));
        //5. 设置mapper和reducer
        job.setMapperClass(DefaultPartitonMapper.class);
        job.setReducerClass(DefaultPartitonReducer.class);

        // 6. 设置mapper的kv类型和reducer的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 对数求余，相同的分到一个文件
        job.setNumReduceTasks(2);

        // 7. 启动job
        boolean b = job.waitForCompletion(true);
        System.out.println(b);

    }

    static class DefaultPartitonMapper extends Mapper<LongWritable, Text,Text, IntWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] arr = value.toString().split("\t");
            context.write(new Text(arr[arr.length-2]),new IntWritable(1));
        }
    }

    static class DefaultPartitonReducer extends Reducer<Text,IntWritable,Text,IntWritable>{
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable v : values) {
                sum += v.get();
            }
            context.write(key,new IntWritable(sum));
        }
    }

}
